package com.kco.generate;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by 666666 on 2017/10/31.
 */
public class MakeAllSql2OneFIle {
    public static void main(String[] args){

        File sqlBaseFile = new File("C:\\Users\\pc\\Documents\\Tencent Files\\568877100\\FileRecv\\bluezone db script");
        File outFile = new File("mysql/all.sql");
        FileUtils.deleteQuietly(outFile);
        if(!sqlBaseFile.exists()){
            System.err.println(sqlBaseFile.getAbsolutePath() + " 不存在.");
            return;
        }
        List<File> sqlFileList = listAllSqlFile(sqlBaseFile);
        System.out.println(sqlFileList);
        sqlFileList.stream().map(file -> {
            StringBuilder sb = new StringBuilder();
            try {
                sb.append("######  start ").append(file.getName()).append(" #####\n")
                        .append(FileUtils.readFileToString(file, Charset.forName("UTF-8")) + "\n")
                        .append("######  end ").append(file.getName()).append(" #####\n\n");
                return sb.toString();
            } catch (IOException e) {
                e.printStackTrace();
                return "";
            }
        }).forEach(context -> {
            try {
                FileUtils.write(outFile, context, Charset.forName("UTF-8"), true);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    private static List<File> listAllSqlFile(File sqlBaseFile) {
        List<File> result = new ArrayList<>();
        File[] sqls = sqlBaseFile.listFiles(file -> file.isDirectory() || file.getName().toLowerCase().endsWith("sql"));
        if (sqls == null || sqls.length == 0){
            return result;
        }
        for(File file : sqls){
            if (file.isDirectory()){
                result.addAll(listAllSqlFile(file));
            }else{
                result.add(file);
            }
        }
        return result;
    }
}
